//
//  RHomeAllVideoViewController.m
//  iPlan
//
//  Created by 侯伟 on 2021/8/24.
//

#import "RHomeAllVideoViewController.h"
#import "WMMenuView.h"
#import "RSearchViewController.h"
#import "EnumObj.h"
#import "RVideoObj.h"
#import "RAllVideoRequest.h"
#import "RFilterConditionRequest.h"
#import "RVideoItemView.h"

@interface RHomeAllVideoViewController ()<WMMenuViewDelegate,WMMenuViewDataSource>{
    
    NSInteger pageIndex;
    NSInteger total;
    
    ConditionArea* _area;
    ConditionYear* _year;
    ConditionType* _type;
    
}

@property(nonatomic,strong) UIScrollView *scrollView;

//@property(nonatomic,strong) MyLinearLayout *contentLayout;

/// -
@property(nonatomic,strong) MyLinearLayout *menuLayout;

/// -
@property(nonatomic,strong) MyFlowLayout *flowLayout;


/// 地区
@property(nonatomic,strong) WMMenuView *areaMenu;

/// 时间
@property(nonatomic,strong) WMMenuView *yearMenu;

/// 分类
@property(nonatomic,strong) WMMenuView *typeMenu;


@property(nonatomic,strong)NSMutableArray* movies;


@property(nonatomic,strong)FilterCondition* condtions;

@end

@implementation RHomeAllVideoViewController

- (NSMutableArray*)movies{
    if(!_movies){
        _movies = [NSMutableArray array];
    }
    return _movies;
}

- (void)loadView{
    [super loadView];
    // 线性布局
    MyLinearLayout *rootLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    rootLayout.backgroundColor = UIColor.whiteColor;
    rootLayout.myMargin = 0;
    [self.view addSubview:rootLayout];
    
    // 线性布局
    MyLinearLayout *menuLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    menuLayout.myHeight = MyLayoutSize.wrap;
    menuLayout.padding = UIEdgeInsetsMake(8, 8, 8, 8);
    menuLayout.myMargin = 0;
    menuLayout.subviewVSpace = 10;
    [rootLayout addSubview:menuLayout];
    _menuLayout = menuLayout;
    
    //底部滚动控件
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.myMargin = 0;
    scrollView.weight = 1.0;
    [rootLayout addSubview:scrollView];
    _scrollView = scrollView;
    
    MJRefreshNormalHeader* header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestData:Refresh];
    }];
    header.arrowView.image = [[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"arrow@2x" ofType:@"png"]] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    header.stateLabel.font = FONT(13);
    header.stateLabel.textColor = COLOR_GRAY_BASE;
    header.lastUpdatedTimeLabel.font = FONT(11);
    header.lastUpdatedTimeLabel.textColor = COLOR_GRAY_BASE;
    header.labelLeftInset = 16;
    scrollView.mj_header = header;
    
    MJRefreshAutoNormalFooter* footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self requestData:LoadMore];
    }];
    footer.automaticallyRefresh = NO;
    footer.stateLabel.font = FONT(13);
    footer.stateLabel.textColor = COLOR_GRAY_BASE;
    scrollView.mj_footer = footer;
    
//    // 线性布局
//    MyLinearLayout *contentLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
//    contentLayout.padding = UIEdgeInsetsZero;
//    contentLayout.myHorzMargin = 0;
//    contentLayout.myTop = 0;
//    contentLayout.heightSize.lBound(scrollView.heightSize, 10, 1);
//    [scrollView addSubview:contentLayout];
//    _contentLayout = contentLayout;
//


    
    // 流式布局
    MyFlowLayout *flowLayout = [MyFlowLayout flowLayoutWithOrientation:MyOrientation_Vert arrangedCount:0];
    flowLayout.myHeight = MyLayoutSize.wrap;
    flowLayout.subviewVSpace = 10;
    flowLayout.subviewHSpace = 10;
    flowLayout.gravity = MyGravity_Horz_Fill;
    flowLayout.padding = UIEdgeInsetsMake(8, 16, 16, 16);
    flowLayout.myMargin = 0;
    [flowLayout setSubviewsSize:PX(105) minSpace:8 maxSpace:CGFLOAT_MAX centered:NO];
    [scrollView addSubview:flowLayout];
    _flowLayout = flowLayout;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNavBar];
    
    [self requestConditions];
    
    [self requestData:Refresh];
}

- (void)setupNavBar{
    
    NSString* title;
    switch (self.VideoType) {
        case VideoType_Movie:
            title = @"电影";
            break;
        case VideoType_TV:
            title = @"电视剧";
            break;
        case VideoType_Anime:
            title = @"动漫";
            break;
        case VideoType_Variety:
            title = @"综艺";
            break;
        default:
            break;
    }

    self.navigationItem.title = title;

    UIBarButtonItem* searchItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"common_search_nav"] style:(UIBarButtonItemStylePlain) target:self action:@selector(searchMoive:)];

    self.navigationItem.rightBarButtonItem = searchItem;
}

- (void)setupMenus{
    // 地区
    WMMenuView *areaMenu = [[WMMenuView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, PX(24))];
    areaMenu.delegate = self;
    areaMenu.dataSource = self;
    areaMenu.style = WMMenuViewStyleFlood;
    areaMenu.layoutMode = WMMenuViewLayoutModeLeft;
    areaMenu.contentMargin = 0;
    areaMenu.lineColor = COLOR_THEME;
    areaMenu.myHeight = PX(24);
    areaMenu.myMargin = 0;
    _areaMenu = areaMenu;
    [self.menuLayout addSubview:areaMenu];
    
    // 年代
    WMMenuView *yearMenu = [[WMMenuView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, PX(24))];
    yearMenu.delegate = self;
    yearMenu.dataSource = self;
    yearMenu.style = WMMenuViewStyleFlood;
    yearMenu.layoutMode = WMMenuViewLayoutModeLeft;
    yearMenu.contentMargin = 0;
    yearMenu.lineColor = COLOR_THEME;
    yearMenu.myHeight = PX(24);
    yearMenu.myMargin = 0;
    _yearMenu = yearMenu;
    [self.menuLayout addSubview:yearMenu];
    
    if(self.VideoType == 1){
        // 类型
        WMMenuView *typeMenu = [[WMMenuView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, PX(24))];
        typeMenu.delegate = self;
        typeMenu.dataSource = self;
        typeMenu.style = WMMenuViewStyleFlood;
        typeMenu.layoutMode = WMMenuViewLayoutModeLeft;
        typeMenu.contentMargin = 0;
        typeMenu.lineColor = COLOR_THEME;
        typeMenu.myHeight = PX(24);
        typeMenu.myMargin = 0;
        _typeMenu = typeMenu;
        [self.menuLayout addSubview:typeMenu];
    }
}

- (void)reloadMenus{
    if(self.condtions){
        [self setupMenus];
    }else{
        self.menuLayout.visibility = MyVisibility_Gone;
    }
}

- (void)reloadData:(RefreshType)refreshType{
    
    if(refreshType == Refresh){
        [self.flowLayout removeAllSubviews];
    }
    for (int i = self.flowLayout.subviews.count; i < self.movies.count; i++) {
        RVideoObj* movie = self.movies[i];
        RVideoItemView* item = [RVideoItemView new];
        item.movie = movie;
        [self.flowLayout addSubview:item];
    }
    
    if(self.movies.count == total){
        [self.scrollView.mj_footer endRefreshingWithNoMoreData];
    }else{
        [self.scrollView.mj_footer resetNoMoreData];
    }
}

- (void)endRefresh{
    [self.scrollView.mj_header endRefreshing];
    [self.scrollView.mj_footer endRefreshing];
}

#pragma mark  --- action
///搜索
- (void)searchMoive:(UIButton*)sender{
    [UIViewController showViewController:[RSearchViewController new] animated:YES];
}

#pragma mark  -- WMMenuViewDelegate,WMMenuViewDataSource
- (void)menuView:(WMMenuView *)menu didSelectedIndex:(NSInteger)index currentIndex:(NSInteger)currentIndex{
    if(menu == self.areaMenu){
        _area = self.condtions.area[index];
    }else if (menu == self.yearMenu){
        _year = self.condtions.year[index];
    }else if (menu == self.typeMenu){
        _type = self.condtions.type[index];
    }

    [self requestData:Refresh];
}

- (CGFloat)menuView:(WMMenuView *)menu itemMarginAtIndex:(NSInteger)index{
    return 8;
}

- (UIFont*)menuView:(WMMenuView *)menu titleFontForState:(WMMenuItemState)state atIndex:(NSInteger)index{
    return FONT_FIT(12);
}

- (CGFloat)menuView:(WMMenuView *)menu widthForItemAtIndex:(NSInteger)index{
    
    NSString* title = [self menuView:menu titleAtIndex:index];
    NSDictionary *attrs = @{NSFontAttributeName: FONT_FIT(12)};
    
    CGFloat itemWidth = [title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attrs context:nil].size.width;
    
    return ceil(itemWidth) + 20;
}

- (UIColor *)menuView:(WMMenuView *)menu titleColorForState:(WMMenuItemState)state atIndex:(NSInteger)index{
    return state == WMMenuItemStateSelected ? COLOR_WHITE:COLOR_BLACK_DARK;
}

- (NSInteger)numbersOfTitlesInMenuView:(WMMenuView *)menu{
    if(menu == self.areaMenu){
        return self.condtions.area.count;
    }else if (menu == self.yearMenu){
        return self.condtions.year.count;
    }else if (menu == self.typeMenu){
        return self.condtions.type.count;
    }
    return 0;
}

- (NSString *)menuView:(WMMenuView *)menu titleAtIndex:(NSInteger)index{
    if(menu == self.areaMenu){
        return self.condtions.area[index].c3_name;
    }else if (menu == self.yearMenu){
        return self.condtions.year[index].name;
    }else if (menu == self.typeMenu){
        return self.condtions.type[index].c2_name;
    }
    return @"";
}

#pragma mark  -- request

- (void)requestConditions{
    RFilterConditionRequest* request = [RFilterConditionRequest new];
    request.action = @"g_c";
    [RequestOperation encryptedRequest:request quite:YES callBack:^(HResponse * _Nullable response) {
        [[response success:^(FilterCondition*  _Nonnull data) {
            self.condtions = data;
            [self reloadMenus];
        }] failure:^(APIError * _Nonnull error) {
            [self reloadMenus];
        }] ;
    }];
}

- (void)requestData:(RefreshType)refreshType{
    NSInteger page = refreshType == Refresh ? 1 : pageIndex+1;
    
    RAllVideoRequest* request = [RAllVideoRequest new];
    request.c_id = self.VideoType;
    request.action = @"t_i_l";
    request.area = _area.c3_id;
    request.year = _year.id;
    if(_type && self.VideoType == 1){
        request.type = _type.c2_id;
    }
    request.page = page;
    
    [RequestOperation encryptedRequest:request quite:YES callBack:^(HResponse * _Nullable response) {
        
        [self endRefresh];
        
        [response success:^(AllMovieList*  _Nonnull data) {
            
            self->total = data.total;
            self->pageIndex = data.current_page;
            
            if(refreshType == Refresh){
                [self.movies removeAllObjects];
            }
            [self.movies addObjectsFromArray:data.lists];
            
            [self reloadData:refreshType];
        }];
    }];
}

//
//- (void)loadMenus{
//    NSMutableArray* areas = [NSMutableArray array];
//    [areas addObject:[EnumObj objWithLable:@"全部地区" value:-1]];
//    [areas addObject:[EnumObj objWithLable:@"大陆" value:0]];
//    [areas addObject:[EnumObj objWithLable:@"美国" value:1]];
//    [areas addObject:[EnumObj objWithLable:@"日本" value:2]];
//    [areas addObject:[EnumObj objWithLable:@"韩国" value:3]];
//    [areas addObject:[EnumObj objWithLable:@"香港" value:4]];
//    _areas = areas;
//
//    NSMutableArray* times = [NSMutableArray array];
//    [times addObject:[EnumObj objWithLable:@"全部时间" value:-1]];
//    [times addObject:[EnumObj objWithLable:@"2021" value:0]];
//    [times addObject:[EnumObj objWithLable:@"2020" value:1]];
//    [times addObject:[EnumObj objWithLable:@"2019" value:2]];
//    [times addObject:[EnumObj objWithLable:@"2018" value:3]];
//    [times addObject:[EnumObj objWithLable:@"2017" value:4]];
//    [times addObject:[EnumObj objWithLable:@"2016" value:5]];
//    [times addObject:[EnumObj objWithLable:@"10-15年" value:6]];
//    [times addObject:[EnumObj objWithLable:@"00年代" value:7]];
//    [times addObject:[EnumObj objWithLable:@"90年代" value:8]];
//    [times addObject:[EnumObj objWithLable:@"80年代" value:9]];
//    _years = times;
//
//    NSMutableArray* types = [NSMutableArray array];
//    [types addObject:[EnumObj objWithLable:@"全部" value:-1]];
//    [types addObject:[EnumObj objWithLable:@"真人秀" value:0]];
//    [types addObject:[EnumObj objWithLable:@"旅行" value:1]];
//    [types addObject:[EnumObj objWithLable:@"脱口秀" value:2]];
//    [types addObject:[EnumObj objWithLable:@"音乐" value:3]];
//    [types addObject:[EnumObj objWithLable:@"综艺" value:4]];
//    [types addObject:[EnumObj objWithLable:@"情感" value:5]];
//    [types addObject:[EnumObj objWithLable:@"搞笑" value:6]];
//    _types = types;
//}
@end
